<template>
  <yy-paging
    v-model="dataList"
    @query="queryList"
    ref="paging"
    :auto="automatic"
    @scroll="scroll"
    :refresher-enabled="false"
  >
    <template #top>
      <u-navbar
        back-text=""
        :is-back="true"
        title="达人入驻"
        :background="{ backgroundColor: isScroll ? '#F2F5F7' : 'transparent' }"
        :border-bottom="false"
        :custom-style="{ transition: 'background-color 0.3s ease-in-out' }"
      >
      </u-navbar>
    </template>
    <template #empty>
      <yy-empty></yy-empty>
    </template>
    <template #loadingMoreNoMore>
      <yy-nomore></yy-nomore>
    </template>
    <view class="flex flex-col gap-3 p-4">
      <view class="text-[.75rem] text-[#8E9299]"> 基础信息</view>
      <!-- 姓名 -->
      <view class="p-4 bg-white rounded-[.5rem] flex items-center">
        <view class="text-[.875rem] text-[#161A24] font-medium tt"> 姓名</view>
        <view>：</view>
        <input
          type="text"
          placeholder="请输入你的真实姓名"
          v-model="form.name"
          maxlength="8"
          class="flex-1 text-[.9375rem] text-[#161A24]"
        />
        <view class="flex items-center pl-4">
          <image src="/static/dddr42.png" v-if="form.name" class="size-4" mode="aspectFill" @click="form.name = ''" />
        </view>
      </view>
      <!-- 手机号码 -->
      <view class="p-4 bg-white rounded-[.5rem] flex items-center">
        <view class="text-[.875rem] text-[#161A24] font-medium tt"> 手机号码</view>
        <view>：</view>
        <input
          type="tel"
          placeholder="请输入你的真实手机号码"
          maxlength="11"
          v-model="form.phoneNumber"
          @blur="checkCellPhoneNumber"
          class="flex-1 text-[.9375rem] text-[#161A24]"
        />
        <view class="flex items-center pl-4">
          <image
            src="/static/dddr42.png"
            v-if="form.phoneNumber"
            class="size-4"
            mode="aspectFill"
            @click="form.phoneNumber = ''"
          />
        </view>
      </view>
      <!-- 邮箱号 -->
      <view class="p-4 bg-white rounded-[.5rem] flex items-center">
        <view class="text-[.875rem] text-[#161A24] font-medium tt"> 邮箱号</view>
        <view>：</view>
        <input
          type="text"
          placeholder="请输入你的真实邮箱号"
          v-model="form.email"
          class="flex-1 text-[.9375rem] text-[#161A24]"
        />
        <view class="flex items-center pl-4">
          <image src="/static/dddr42.png" v-if="form.email" class="size-4" mode="aspectFill" @click="form.email = ''" />
        </view>
      </view>
      <!-- 地区 -->
      <view class="p-4 bg-white rounded-[.5rem] flex items-center">
        <view class="text-[.875rem] text-[#161A24] font-medium tt"> 地区</view>
        <view>：</view>
        <view class="flex-1 text-[.9375rem] text-[#161A24]" @click="area.openArea = true">
          <text v-if="!area.value" class="text-[#8E9299]">请输入你的真实地区</text>
          <text v-else>{{ area.value }}</text>
        </view>
        <view class="flex items-center pl-4">
          <image
            src="/static/dddr42.png"
            v-if="area.value"
            class="size-4"
            mode="aspectFill"
            @click.stop="area.value = ''"
          />
        </view>
      </view>
      <view class="text-[.75rem] text-[#8E9299]"> 身份信息</view>
      <view class="p-4 bg-white rounded-[.5rem] flex items-center">
        <view class="text-[.875rem] text-[#161A24] font-medium tt">身份证号</view>
        <view>：</view>
        <input
          type="idcard"
          placeholder="请输入你的真实身份证号"
          v-model="form.idNumber"
          class="flex-1 text-[.9375rem] text-[#161A24]"
          @blur="checkIdNumber"
        />
        <view class="flex items-center pl-4">
          <image
            src="/static/dddr42.png"
            v-if="form.idNumber"
            class="size-4"
            mode="aspectFill"
            @click="form.idNumber = ''"
          />
        </view>
      </view>
      <view class="grid grid-cols-2 gap-3">
        <view class="flex flex-col col-span-1 gap-2">
          <view
            class="w-full h-[6.375rem] rounded-[.75rem] border-[.0625rem] border-dashed relative overflow-hidden border-[#E5E6EB] bg-[#FBFBFC] flex justify-center items-center"
          >
            <u-image
              src="/static/dddr10.png"
              class="!size-10"
              v-if="!form.id_card_front"
              mode="aspectFill"
              @click="uploads(1)"
            />
            <u-image :src="form.id_card_front" class="!size-full rounded-[.75rem]" v-else />
            <view
              @click="deleteImage('front')"
              v-if="form.id_card_front"
              class="w-[1.25rem] h-[1.25rem] bg-[#000000]/40 rounded-[0rem_.5rem_0rem_.5rem] absolute right-0 top-0 flex justify-center items-center"
            >
              <u-icon name="close" color="#fff" size="20"></u-icon>
            </view>
          </view>
          <view class="text-[.6875rem] text-[#8E9299]">身份证正面</view>
        </view>
        <view class="flex flex-col col-span-1 gap-2">
          <view
            class="w-full h-[6.375rem] rounded-[.75rem] border-[.0625rem] border-dashed relative overflow-hidden border-[#E5E6EB] bg-[#FBFBFC] flex justify-center items-center"
          >
            <u-image src="/static/dddr10.png" class="!size-10" @click="uploads(2)" v-if="!form.id_card_back" />
            <u-image :src="form.id_card_back" class="!size-full rounded-[.75rem]" v-else />
            <view
              @click="deleteImage('back')"
              v-if="form.id_card_back"
              class="w-[1.25rem] h-[1.25rem] bg-[#000000]/40 rounded-[0rem_.5rem_0rem_.5rem] absolute right-0 top-0 flex justify-center items-center"
            >
              <u-icon name="close" color="#fff" size="20"></u-icon>
            </view>
          </view>
          <view class="text-[.6875rem] text-[#8E9299]">身份证反面</view>
        </view>
      </view>
    </view>
    <template #bottom>
      <view class="pb-env">
        <view class="px-4 py-3">
          <!-- #99DBDC -->

          <view class="flex justify-center">
            <view
              :class="isValid ? 'bg-[#99DBDC]' : 'bg-[#00A9AB]'"
              class="h-[2.75rem] w-full rounded-full flex items-center justify-center btn"
              @click="bindNow"
            >
              <text class="text-[1rem] text-[#E5F6F6]">提交申请</text>
            </view>
          </view>
        </view>
      </view>
    </template>
    <!-- 地区 -->
    <u-picker v-model="area.openArea" title="选择城市" mode="region" @confirm="areaConfirmation"></u-picker>
  </yy-paging>
</template>

<script>
  export default {
    data() {
      return {
        isScroll: false, // 是否滚动
        dataList: [], // 数据列表
        automatic: false, // 是否自动加载
        form: {
          name: '',
          phoneNumber: '',
          email: '',
          idNumber: '', //110102199005206666
          province: '',
          city: '',
          district: '',
          province_code: '',
          city_code: '',
          district_code: '',
          id_card_front: '',
          id_card_back: ''
        },
        isValid: false,
        area: {
          openArea: false,
          value: ''
        }
      }
    },

    watch: {
      form: {
        immediate: true,
        deep: true,
        handler(newValue, oldValue) {
          this.isValid = vk.pubfn.isNullOneByObject(newValue)
        }
      }
    },
    onLoad(options) {
      // #ifdef H5
      // 模拟初始化数据
      this.form = {
        name: '张三',
        phoneNumber: '13800138000',
        email: 'zhangsan@example.com',
        idNumber: '110102198805209696',
        province: '北京市',
        city: '北京市',
        district: '东城区',
        province_code: '110000',
        city_code: '110100',
        district_code: '110101',
        id_card_front: 'https://basan.oss-cn-chengdu.aliyuncs.com/storage/settled/20250723/1753252934985_JM7EF7Ca.jpg',
        id_card_back: 'https://basan.oss-cn-chengdu.aliyuncs.com/storage/settled/20250723/1753252937884_WCDkYrAa.jpg'
      }
      // #endif
    },
    methods: {
      checkIdNumber() {
        // 验证身份证号码格式
        const idNumberPattern = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
        if (!this.form.idNumber) return
        if (!idNumberPattern.test(this.form.idNumber)) {
          vk.toast('请输入正确的身份证号码')
          return
        }

        // 验证身份证号码的校验码
        const idCardVerify = idCard => {
          const factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
          const parity = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']
          let sum = 0
          let ai = 0
          let wi = 0
          for (let i = 0; i < 17; i++) {
            ai = idCard[i]
            wi = factor[i]
            sum += ai * wi
          }
          const last = parity[sum % 11]
          return last === idCard[17].toUpperCase()
        }

        if (this.form.idNumber.length === 18) {
          if (!idCardVerify(this.form.idNumber)) {
            vk.toast('身份证号码校验失败')
            return
          }
        }
      },
      checkCellPhoneNumber() {
        // 验证手机号码格式
        if (this.form.phoneNumber) {
          const phoneReg = /^1[3-9]\d{9}$/
          if (!phoneReg.test(this.form.phoneNumber)) {
            vk.toast('请输入正确的手机号码')
            return false
          }
          return true
        }
      },
      deleteImage(e) {
        this.form[`id_card_${e}`] = ''
      },
      async uploads(e) {
        try {
          const [url] = await vk.myfn.uploadImage({
            count: 1,
            topic: 'settled'
          })
          // 根据传入的参数e判断更新不同的身份证照片
          this.form[e === 1 ? 'id_card_front' : 'id_card_back'] = url
        } catch (err) {
          console.error('上传失败:', err)
        }
      },
      areaConfirmation(e) {
        this.form.province = e.province.name
        this.form.city = e.city.name
        this.form.district = e.area.name
        this.form.province_code = e.province.code
        this.form.city_code = e.city.code
        this.form.district_code = e.area.code
        this.area.value = [e.province.name, e.city.name, e.area.name].join('-')
      },
      async bindNow() {
        vk.pubfn.debounce(async () => {
          if (vk.pubfn.isNullOneByObject(this.form)) {
            vk.toast('请填写完整后再进行提交')
            return
          }
          vk.showLoading('提交中...')
          let res = await api.joinDaren({
            realname: this.form.name,
            mobile: this.form.phoneNumber,
            email: this.form.email,
            id_card: this.form.idNumber,
            province: this.form.province,
            city: this.form.city,
            district: this.form.district,
            province_code: this.form.province_code,
            city_code: this.form.city_code,
            district_code: this.form.district_code,
            id_card_front: this.form.id_card_front,
            id_card_back: this.form.id_card_back
          })
          vk.hideLoading()
          if (!res.code) return
          vk.vuex.dispatch('$user/getUserInfo')
          vk.reLaunch('/pages/my/index')
        }, 500)
      },
      scroll(e) {
        this.isScroll = e.detail.scrollTop > 0
      },
      async queryList(page, limit) {
        this.$refs.paging.complete([1, 1, 1])
      }
    }
  }
</script>

<style lang="scss" scoped>
  .tt {
    width: 4.375rem;
    text-align-last: justify;
  }
</style>
